package com.sleepcamel.rest.domain.sourcegenerator;

import java.util.HashMap;
import java.util.Map;

import com.sleepcamel.rest.domain.ISourceCodeGenerable;
import com.sleepcamel.rest.domain.Mapping;
import com.sleepcamel.rest.domain.method.NonRESTMethod;
import com.sleepcamel.rest.domain.method.RESTMethod;
import com.sleepcamel.rest.domain.method.parameter.MethodParameter;
import com.sleepcamel.rest.domain.method.parameter.RESTMethodParameter;

public class SourceCodeGeneratorProvider {

	private static SourceCodeGeneratorProvider instance;
	private static Map<Class<? extends ISourceCodeGenerable>, Class<? extends ISourceCodeGenerator>> generatorMap;

	private SourceCodeGeneratorProvider(){
		generatorMap = new HashMap<Class<? extends ISourceCodeGenerable>, Class<? extends ISourceCodeGenerator>>();
		registerGenerator(Mapping.class, MappingSourceGenerator.class);
		registerGenerator(RESTMethod.class, MethodSourceGenerator.class);
		registerGenerator(NonRESTMethod.class, MethodSourceGenerator.class);
		registerGenerator(RESTMethodParameter.class, MethodParameterSourceGenerator.class);
		registerGenerator(MethodParameter.class, MethodParameterSourceGenerator.class);
	}
	
	private void registerGenerator(Class<? extends ISourceCodeGenerable> domainClass, Class<? extends ISourceCodeGenerator> sourceGenerator) {
		generatorMap.put(domainClass, sourceGenerator);
	}

	public static SourceCodeGeneratorProvider getInstance(){
		if ( instance == null ){
			instance = new SourceCodeGeneratorProvider();
		}
		return instance;
	}

	public ISourceCodeGenerator getGeneratorFor(Object data) {
		ISourceCodeGenerator generator = null;
		if ( data != null ){
			Class<? extends ISourceCodeGenerator> generatorClass = generatorMap.get(data.getClass());
			if ( generatorClass != null ){
				try {
					generator = generatorClass.newInstance();
				} catch (Exception e) {
				}
			}
		}
		return generator;
	}
}
